package hxdb

import (
  "database/sql"
)

// convert *sql.Rows to []map[string]interface{}
func rowsMapper(rows *sql.Rows) ([]map[string]interface{}, error) {
  // get columns
  cols, err := rows.Columns()
  if err != nil {
    return nil, err
  }
  // set temp interface saver
  values := make([]interface{}, len(cols))
  tmpItf := make([]interface{}, len(values))
  for i, _ := range tmpItf {
    tmpItf[i] = &values[i]
  }
  // set returning result
  rs := make([]map[string]interface{}, 0)
  for rows.Next() {
    rows.Scan(tmpItf...)
    rowRst := make(map[string]interface{})
    // make all column values to string and append to result
    for i := range values {
      if values[i] == nil {
        continue
      }
    
      // only []byte, int64, float64 can get from mysql driver
      // for common use, just convert []byte to string,
      // then string can be converted to another data type when needed
      switch val := values[i].(type) {
      case []byte:
        rowRst[cols[i]] = string(val)
      default:
        rowRst[cols[i]] = val
      }
    }
    rs = append(rs, rowRst)
  }

  if len(rs) > 0 {
    return rs, nil
  }
  return nil, sql.ErrNoRows
}
